package com.cby.ssm.controller;

import com.cby.common.ThisSystemException;
import com.cby.ssm.entity.RoleEntity;
import com.cby.ssm.entity.UserEntity;
import com.cby.ssm.entity.User_RoleEntity;
import com.cby.ssm.service.RoleService;
import com.cby.ssm.service.UserService;
import com.cby.ssm.service.User_RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 13296 on 2017/7/14.
 */
@Controller
public class UserHandler {
    @Autowired
    UserService fun;
    @Autowired
    RoleService rfun;
    @Autowired
    User_RoleService urfun;


    @ModelAttribute
    public String getNotDeleteIds(HttpServletRequest request){
        HttpSession session = request.getSession();
        UserEntity u=(UserEntity)session.getAttribute("currentUser");
        //System.out.println("idOfcurrentUser:"+u.getId());
        return u.getId();
    }

    /**
     * 修改密码
     * @return
     */
    @RequestMapping(method=RequestMethod.GET,path="/updatepassword.do")
    public String updatepasswordView(){
        return null;
    }

    @RequestMapping(method=RequestMethod.POST,path="/updatepassword.do")
    public String updatepassword(String oldPassword,String newPassword,String newPasswordConfirm,Model model,HttpServletRequest request)throws Exception{
        HttpSession session=request.getSession();
        UserEntity u=(UserEntity)session.getAttribute("currentUser");
        try{
            fun.updatePassword(u.getId(),oldPassword, newPassword, newPasswordConfirm);
        }catch(ThisSystemException e){
            model.addAttribute("message", e.getMessage());
            return "updatepassword";
        }
        model.addAttribute("message", "修改成功，请重新登录");
        return "redirect:/login.jsp";
    }

    /**
     * 查找用户
     * @return
     */

    @RequestMapping(method=RequestMethod.GET,path="/searchUser.do")
    public void  searchUser(int pn, String searchKey,Model model,String searchMethod,HttpServletRequest request)throws Exception{
        searchUserView(pn,searchKey,model,searchMethod,request);
    }

    @RequestMapping(method= RequestMethod.POST,path="/searchUser.do")
    public String searchUserView(int pn, String searchKey, Model model,String searchMethod, HttpServletRequest request){
        //HttpSession session = request.getSession();
        List<UserEntity> pageList = new ArrayList<>();
        try {
            //查询角色
            List<RoleEntity> roleList = rfun.searchAllRole();
            request.setAttribute("allRoles",roleList);

            //查询用户
            model.addAttribute("searchKey",searchKey);
            PageHelper.startPage(pn, 10);
            List<UserEntity> list = fun.searchUsers(searchKey);
            //查询每个用户对应的角色
            for(UserEntity u:list){
                List<User_RoleEntity> roleListOfUserId = urfun.SearchAllRolesByUserId(u.getId());
                //System.out.println(u.getId()+"roleListOfUserIdSize:"+roleListOfUserId.size());
                request.setAttribute("roleListOfUserId"+u.getId(),roleListOfUserId);
            }

            PageInfo<UserEntity> pageInfo = new PageInfo<>(list);
            //System.out.println(pageInfo.getPages());
            pageList.addAll(pageInfo.getList());
            request.setAttribute("pageCount",pageInfo.getPages());
            request.setAttribute("pageList",pageList);
            request.setAttribute("pn",pn);
        }catch (Exception e){
            model.addAttribute("message",e.getMessage());
            //System.out.println("kong");
            return "redirect:/deleteUser.do?pn=1";
        }
        return "searchUser";
    }

    /**
     * 删除用户
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(method= RequestMethod.GET,path="/deleteUser.do")
    public String deleteUserView(int pn,String id,String message, Model model,HttpServletRequest request){
        //HttpSession session = request.getSession();
        List<UserEntity> pageList = new ArrayList<>();
        try {
            //查询角色
            List<RoleEntity> roleList = rfun.searchAllRole();
            request.setAttribute("allRoles",roleList);

            //查询所有用户
            fun.deleteUser(id,getNotDeleteIds(request));
            PageHelper.startPage(pn, 10);
            List<UserEntity> list = fun.searchAllUser();
            //查询每个用户对应的角色
            for(UserEntity u:list){
                List<User_RoleEntity> roleListOfUserId = urfun.SearchAllRolesByUserId(u.getId());
                //System.out.println(u.getId()+"roleListOfUserIdSize:"+roleListOfUserId.size());
                request.setAttribute("roleListOfUserId"+u.getId(),roleListOfUserId);
            }

            PageInfo<UserEntity> pageInfo = new PageInfo<>(list);
            pageList.addAll(pageInfo.getList());

            request.setAttribute("pageCount",pageInfo.getPages());
            request.setAttribute("pageList",pageList);
            request.setAttribute("pn",pn);
            if(message.equals("notDelete")){
                model.addAttribute("message","notDelete");
            }

        } catch (Exception e) {
            return "redirect:/deleteUser.do?pn="+pn+"&message="+e.getMessage();
        }
        return null;
    }
    @RequestMapping(method=RequestMethod.GET,path="/deleteUserOfSearchView.do")
       public String  deleteUser(String id,int pn,String searchKey,Model model,HttpServletRequest request){
        HttpSession session = request.getSession();
        try {
            searchKey = new String(searchKey.getBytes("UTF-8"),"ISO-8859-1");
            fun.deleteUser(id,getNotDeleteIds(request));
            //System.out.println("redirect:/searchUser.do?pn="+pn+"&searchKey="+searchKey);

        } catch (Exception e) {
            session.setAttribute("message",e.getMessage());
            return "redirect:/searchUser.do?pn="+pn+"&searchKey="+searchKey;
            //e.printStackTrace();
        }
        return "redirect:/searchUser.do?pn="+pn+"&searchKey="+searchKey;
    }

    /**
     * 修改用户信息
     * @param id
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(method= RequestMethod.GET,path="/editUser.do")
    public String editUserView(String pn,String searchKey,String action,String id,Model model,HttpServletRequest request){
        HttpSession session = request.getSession();
        UserEntity u = null;
        try {
            u = fun.searchUser(id);
            model.addAttribute("u",u);
            //model.addAttribute("pn",pn);
            session.setAttribute("pn",pn);
            //model.addAttribute("searchKey",searchKey);
            session.setAttribute("searchKey",searchKey);
            if(action.equals("searchUser")){
                //model.addAttribute("action",action);
                session.setAttribute("action",action);
            }else{
                //model.addAttribute("action","deleteUser");
                session.setAttribute("action","deleteUser");
            }
        } catch (Exception e) {
            model.addAttribute("message",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
    @RequestMapping(method=RequestMethod.POST,path="/editUser.do")
    public String editUser(String id, String account, String name, String sex,
                           String telephone, String email, String address, Model model, HttpServletRequest request){
        HttpSession session=request.getSession();
        try {
            UserEntity u=fun.searchUser(id);
            u.setAccount(account.trim());
            u.setId(id.trim());
            u.setName(name);
            u.setSex(sex);
            u.setTelephone(telephone);
            u.setEmail(email);
            u.setAddress(address);

            UserEntity uu = fun.editUser(u);
            //model.put("u",uu);
            model.addAttribute("u",uu);
        }catch (Exception e){
            model.addAttribute("message",e.getMessage());
        }
        model.addAttribute("message", "修改成功！");
        return "editUser";
    }
}
